package com.atguigu.gmall.common.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: lx
 * @Time: 11:41
 * @Description:
 *
 *   拦截器
 *   远程调用请求
 *
 *   工具类
 *
 */
public class FeignInterceptor implements RequestInterceptor {

    //拦截器方法   RequestTemplate ：远程调用请求对象
    @Override
    public void apply(RequestTemplate requestTemplate) {

        //1:当前请求对象头中用户ID 传递给 远程调用请求对象的头中
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();

        if(requestAttributes != null){
            //当前微服务的请求对象
            HttpServletRequest request = requestAttributes.getRequest();
            if(null != request){
                //网关传递过来的真实用户ID
                String userId = request.getHeader("userId");
                if(!StringUtils.isEmpty(userId)){
                    requestTemplate.header("userId",userId);
                }
                //网关传递过来的临时用户ID
                String userTempId = request.getHeader("userTempId");
                if(!StringUtils.isEmpty(userTempId)){
                    requestTemplate.header("userTempId",userTempId);
                }
            }
        }



    }
}
